package com.spirit.spring.study.context.proxy.cglibproxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @auth eric-好好学习，天天向上!
 * @date 2022/4/5
 * @description
 */
public class CglibProxyDemo {

    public static void main(final String[] args) {
        // 创建原始类
        final UserService userService = new UserService();

        /**
         * cglib 创建动态代理
         * 1. 设置classLoader
         * 2. 设置原始类
         * 3. 设置功能增强
         */
        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(CglibProxyDemo.class.getClassLoader());
        enhancer.setSuperclass(userService.getClass());

        MethodInterceptor interceptor = new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                // 增强操作
                Object ret = method.invoke(userService, objects);
                // 增强操作
                return ret;
            }
        };

        enhancer.setCallback(interceptor);
        UserService userProxy = (UserService) enhancer.create();
        userProxy.login("eric", "xxxx");
    }


}
